package com.qyy.remotemonitor.ui.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.Nullable;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.qyy.remotemonitor.common.ui.BaseService;
import com.qyy.remotemonitor.common.util.LocationManagerUtil;
import com.qyy.remotemonitor.http.bean.HttpOperationBean;
import com.qyy.remotemonitor.http.bean.HttpUploadCallRecordsBean;
import com.qyy.remotemonitor.model.contract.remotemonitor.RemoteMonitorContract;
import com.qyy.remotemonitor.model.presenter.remotemonitor.RemoteMonitorPresenter;
import com.wang.android.library.network.eventbus.WHttpEventBean;

import java.text.SimpleDateFormat;
import java.util.Locale;

/**
 * Created by qinyy on 2018/10/2.
 */

public class RemoteMonitorService extends BaseService<RemoteMonitorPresenter> implements RemoteMonitorContract.View
{

    @Override
    public void initInject()
    {
        getServiceComponent().inject(this);
    }

    @Override
    public void initTodo()
    {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
        {
            // 8.0以上该服务为前台服务，否则无法被jobservice在后台拉起
            NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            // notification id
            final String channelId = "com.qyy.remoteMonitor";
            // create notification channel
            NotificationChannel
                    mChannel = new NotificationChannel(channelId, "安全防护正在运行", NotificationManager.IMPORTANCE_LOW);
            mNotificationManager.createNotificationChannel(mChannel);
            // set channel id
            Notification status = new Notification.Builder(RemoteMonitorService.this).setChannelId(channelId).build();
            // start for foreground process
            startForeground(1, status);

        }

        LocationManagerUtil.getInstance(getApplication()).initLocation();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
    {
        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent)
    {
        return null;
    }


    private final BroadcastReceiver mReceiver = new BroadcastReceiver()
    {
        @Override
        public void onReceive(Context context, Intent intent)
        {
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_TIME_TICK))
            {
                LogUtils.d("receive time tick! begin to query operation!");
                getPresenter().queryOperation();
                // 每分钟更新一次通话记录数据库
                getPresenter().updateCallsHistory();
            }
        }
    };




    @Override
    public void showBaseDialog()
    {

    }

    @Override
    public void dismissBaseDialog()
    {

    }

    @Override
    public void showNetDialog()
    {

    }

    @Override
    public void dismissNetDialog()
    {

    }

    @Override
    public void onEvent(WHttpEventBean wNetEventBean)
    {

    }

    @Override
    public void register()
    {
        IntentFilter filter=new IntentFilter();
        filter.addAction(Intent.ACTION_TIME_TICK);
        registerReceiver(mReceiver,filter);
    }

    @Override
    public void unregister()
    {
        unregisterReceiver(mReceiver);
    }

    @Override
    public void showErrorMsg(String msg)
    {

    }

    @Override
    public void stateError()
    {

    }

    @Override
    public void queryOperationSuccess(HttpOperationBean bean)
    {
        LogUtils.d("queryOperationSuccess ");
        if(bean.getNeeduploadlocation())
        {
            // 如果需要上传位置信息
            getPresenter().uploadLocation(LocationManagerUtil.getInstance(getApplication()).getLat(),LocationManagerUtil.getInstance(getApplication()).getLon(),bean.getOperationid());
        }

        if(bean.getNeeduploadrecords())
        {
            long startTime = TimeUtils.string2Millis(bean.getRecordsbegindate(), new SimpleDateFormat("yyyy-MM-dd", Locale
                    .getDefault()));
            long endTime = TimeUtils.string2Millis(bean.getRecordsenddate(), new SimpleDateFormat("yyyy-MM-dd", Locale
                    .getDefault()));
            getPresenter().uploadCallRecord(startTime,endTime,bean.getOperationid());
          //  bean.getRecordsbegindate()
        }
    }

    @Override
    public void queryOperationFailure(String errorCode, String errorMsg)
    {
        LogUtils.d("queryOperationFailure errorCode " + errorCode + " errorMsg " + errorMsg);
    }

    @Override public void uploadCallRecordSuccess(HttpUploadCallRecordsBean bean)
    {
        LogUtils.d("uploadCallRecordSuccess " );
    }

    @Override public void uploadCallRecordFailure(String errorCode, String errorMsg)
    {
        LogUtils.d("uploadCallRecordFailure errorCode " + errorCode + " errorMsg " + errorMsg);
    }
}
